package com.erclab.internal.xpresso.webapp.servlets;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.erclab.internal.xpresso.FormFactory;
import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.exceptions.ObjectCreatorException;
import com.erclab.internal.xpresso.formelements.FormElement;
import com.erclab.internal.xpresso.forms.Form;
import com.erclab.internal.xpresso.forms.FormParameters;
import com.erclab.internal.xpresso.security.User;
import com.erclab.internal.xpresso.util.ObjectCreator;
import com.erclab.internal.xpresso.util.NewObjectAttributes;

/**
 * @version 	1.0
 * @author
 */
public class ObjectCreatorProcessor extends HttpServlet {

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

		FormParameters parameters = new FormParameters();
		parameters.setUser((User)req.getSession().getAttribute("user"));
		
		Form theForm = null;
		try {
			theForm = FormFactory.loadForm(req.getParameter("formName"));
		} catch (FormException e) {
			throw new ServletException("Could not load form '" + req.getParameter("formName") + "': " + e);
		}
		
		// TODO: Validation of data
		// DataValidator dv = new DataValidator();
		
		
		ObjectCreator oc = Settings.getObjectCreator();
		
		// New object Attributes
		NewObjectAttributes noa = new NewObjectAttributes();  
		
		// Set the attributes
		for (Iterator iter = theForm.getFormElements().iterator(); iter.hasNext();) {
			FormElement fe = (FormElement)iter.next();
			setNewObjectAttributes(noa, fe, req);
		}		
		
		if(noa.getAction() == null){
			req.setAttribute("Status", "You must specify an action");
		} else if (noa.getAction().equals("createForm")){
			try {
				oc.createForm(noa.getObjectName(), noa.getObjectTarget(), noa.getUniqueKeyName(), 
								noa.getParentKeyName(), 
								Integer.parseInt(noa.getIdDatasourceRead()), 
								Integer.parseInt(noa.getIdDatasourceWrite()));
			} catch (ObjectCreatorException e) {
				throw new ServletException(e);
			}
		} else if (noa.getAction().equals("createReport")){
			try {
				oc.createReport(noa.getObjectName(), noa.getObjectTarget(), noa.getReportQuery(),
							noa.getUniqueKeyName(), 
							Integer.parseInt(noa.getIdDatasourceRead()), 
							Integer.parseInt(noa.getIdDatasourceWrite()));
			} catch (ObjectCreatorException e) {
				throw new ServletException(e);
			}
		}

		req.setAttribute("Status", "Object " + noa.getObjectName() + " created succesfully");

		resp.sendRedirect(getForwardPage(theForm.getForwardUrl(), req.getSession()));

	}


	protected void setNewObjectAttributes(NewObjectAttributes noa, FormElement fe, HttpServletRequest request){
		String columnName = fe.getDestinationColumn();
		if (columnName.equals("objectName")){
			noa.setObjectName(request.getParameter("Field" + fe.getIdFormElement()));
		} else if (columnName.equals("objectTarget")){
			noa.setObjectTarget(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("reportQuery")){
			noa.setReportQuery(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("uniqueKeyName")){
			noa.setUniqueKeyName(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("idDataSourceRead")){
			noa.setIdDatasourceRead(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("idDataSourceWrite")){
			noa.setIdDatasourceWrite(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("parentKeyName")){
			noa.setParentKeyName(request.getParameter("Field" + fe.getIdFormElement()));
		} else if(columnName.equals("action")){
			noa.setAction(request.getParameter("Field" + fe.getIdFormElement()));
		}
	}

	/**
	 * @param string
	 * @return
	 */
	// TODO: Extract this method to a separate class to avoid repetition in this class and in the
	// FormProcessor class as well
	private String getForwardPage(String forwardUrl, HttpSession session) {
		String url = null;
		if(forwardUrl.equalsIgnoreCase("-param:previousUrl-")){
			url = (String)session.getAttribute("forwardUrl");
			if (url == null){
				return forwardUrl;
			}
		} else {
			url = forwardUrl;
		}
		
		return url;
	}

}
